package com.jlnk.androidfmc.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.fragment.app.Fragment;

import com.jlnk.androidfmc.R;
import com.jlnk.androidfmc.entity.News;
import com.jlnk.androidfmc.entity.ZNews;


public class NewsDetailFragment extends Fragment {

    private News mNews;


    // 在 NewsDetailFragment.java 中
    public static NewsDetailFragment newInstance(ZNews news) {
        NewsDetailFragment fragment = new NewsDetailFragment();
        Bundle args = new Bundle();
        args.putParcelable("news", news); // 这里可以直接传递 ZNews 对象
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mNews = getArguments().getParcelable("news");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.news_detail, container, false);

        WebView webView = view.findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);

        // 加载本地HTML文件
        String path = "file:///android_asset/news_detail.html";
        webView.loadUrl(path);

        // 设置WebViewClient，以便处理加载完成事件
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // 将新闻详情传递给HTML页面
                injectJavaScript(view, mNews);
            }
        });

        return view;
    }

    private void injectJavaScript(WebView webView, News news) {
        String javascript = "var news = " + news.toJson() + ";"
                + "document.getElementById('news-title').textContent = news.title;"
                + "document.getElementById('news-image').src = news.image;"
                + "document.getElementById('news-content').innerHTML = news.content;";
        webView.evaluateJavascript(javascript, null);
    }
}
